package com.common.utils;

import sun.misc.BASE64Encoder;

import java.io.*;
import java.util.*;

public class PythonUtil {
//    private final static String python_root_path = "C:\\Users\\tm\\AppData\\Local\\Programs\\Python\\Python39\\python";
//    private final static String python_code_path = "D:\\test\\";

    private final static String python_root_path = "python";
    private final static String python_code_path = "/scc/oams/";

    public static void main(String[] args) {
/*        String str = "C:\\Users\\tm\\Desktop\\20231017115240.jpg";
        System.out.println(imageBase64(str));*/
        /**
         * 计算维修人员
         * 6 month
         * 4 day
         * 411623 quhao区
         * 0.611255186 选择4号以前的数据中gps_mach_count_one_day相加
         * 0.377726083 选择4号以前的数据中gps_mach_cr_num_one_day相加
         * 0.25 选择4号以前的数据中man_local_num_one_day相加
         */
//        callRepairUser("6 4 411623 0.611255186 0.377726083 0.25");

//        callDD();
//        callDynamicOptimization();
//        callPathMap("5 湖南");
        callPathPlanning();
    }

    /**
     * 计算维修人员管理
     *
     * @author tm
     * @date 2023-10-26 16:26
     */
    public static List<String> callRepairUser(String params) {
        List<String> list = new ArrayList<>();
        String path = python_code_path + "gpsPython";
        String file = "test.py";
        String result = callPython(path, file, params);
        System.out.println("返回的数据： " + result);
        if(result.length()>0){
            int i = result.indexOf("[");
            int j = result.indexOf("]");
            String data1 = result.substring(i+1,j);
            list.add(data1);
            result = result.substring(j+1,result.length());
            int m = result.indexOf("[");
            int n = result.indexOf("]");
            String data2 = result.substring(m+1,n);
            list.add(data2);
        }
        return list;
    }

    /**
     * 区域服务调度算法
     * @author tm
     * @date 2023-10-26 17:41
     */
    public static List<Map<String,String>> callDD(){
        List<Map<String,String>> list = new ArrayList<>();
        String path = python_code_path+"pathAlgorithm";
        String file = "dd.py";
        String params = "";
        String result = callPython(path, file, params);
        System.out.println("返回的数据： " + result);
        if(result.length()>0){
            String[] str = result.split("array\\(");
            System.out.println(str.length);
            String str1 = str[1].replaceAll("\\)","");
            String str2 = str[2].replaceAll("\\),","");
            String[] names = str1.split(",");
            String[] ids = str2.split("],\\[");
            for(int i =0;i<names.length;i++){
                String name = names[i].replaceAll("\\[","").replaceAll("]","");
                String id = ids[i].replaceAll("\\[","").replaceAll("]","");
                Map<String,String> map = new HashMap<>();
                map.put("name",name);
                map.put("id",id);
                list.add(map);
            }
        }
        return list;
    }

    /** 
     * 订单排序算法
     * @author tm
     * @date 2023-10-26 17:41
     */
    public static List<String> callDynamicOptimization(){
        List<String> list = new ArrayList<>();
        String path = python_code_path+"pathAlgorithm";
        String file = "dynamicOptimization.py";
        String params = "";
        String result = callPython(path, file, params);
        System.out.println("返回的数据： " + result);
        if(result.length()>0){
            result = result.replaceAll("\\(array\\(","").replaceAll("\\)","");
            String[] str = result.split("],\\[");
            for(String s:str){
                list.add(s.replaceAll("\\[","").replaceAll("]",""));
            }
        }
        return list;
    }


    /**
     * 服务车分布算法
     * @author tm
     * @date 2023-10-26 17:41
     */
    public static List<Map<String,String>> callPathMap(String params){
        List<Map<String,String>> list = new ArrayList<>();
        String path = python_code_path+"pathAlgorithm";
        String file = "pathmapnew.py";
        String result = callPython(path, file, params);
        System.out.println("返回的数据： " + result);
        if(result.length()>0){
            String[] str = result.split("array\\(");
            result = str[2].replaceAll("\\)","");
            String[] dataStr = result.split("],\\[");
            for(String s:dataStr){
                String[] area = s.split(",");
                String name = area[0].replaceAll("\\[","").replaceAll("]","");
                String number = area[1].replaceAll("\\[","").replaceAll("]","");
                Map<String,String> map = new HashMap<>();
                map.put("name",name);
                map.put("number",number);
                list.add(map);
            }
        }
        return list;
    }


    /**
     * 最优路径算法
     * @author tm
     * @date 2023-10-26 17:41
     */
    public static List<Map<String,String>> callPathPlanning(){
        List<Map<String,String>> list = new ArrayList<>();
        String path = python_code_path+"pathAlgorithm";
        String file = "pathPlanning.py";
        String params = "";
        String result = callPython(path, file, params);
        System.out.println("返回的数据： " + result);
        if(result.length()>0){
            String[] str = result.split("\\),array\\(");//0订单集合，1总运输距离，2服务车编号
            String[] ids = str[0].replaceAll("\\(array\\(","").split("],\\[");
            String[] cars = str[2].replaceAll("\\)","").split(",");
            for(int i =0;i<cars.length;i++){
                String car = cars[i].replaceAll("\\[","").replaceAll("]","");
                String id = ids[i].replaceAll("\\[","").replaceAll("]","");
                Map<String,String> map = new HashMap<>();
                map.put("car",car);
                map.put("id",id);
                list.add(map);
            }
        }
        return list;
    }

    private static String callPython(String path, String file, String params) {
        String result = "";
        try {
            String code = python_root_path + " " + path + "/" + file;//"C:\\Users\\tm\\AppData\\Local\\Programs\\Python\\Python39\\python D:\\test\\gpsPython\\test.py 6 4 411623 0.611255186 0.377726083 0.25";
            if (!"".equals(params)) code += " " + params;
//            code = "C:\\Users\\tm\\AppData\\Local\\Programs\\Python\\Python39\\python D:\\test\\pathAlgorithm\\dd.py";
            String str = String.format(code);
//            str = "python --version";
            System.out.println(str);
            Process proc = Runtime.getRuntime().exec(str);//执行脚本
            proc.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream(), "UTF-8"));
            String line = "";
            while ((line = reader.readLine()) != null) {
                result += line + "";
            }
            reader.close();
            proc.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void testPython1() {
        String result = "";
        try {
            String code = "C:\\Users\\tm\\AppData\\Local\\Programs\\Python\\Python39\\python D:\\test\\gpsPython\\test.py 6 4 411623 0.611255186 0.377726083 0.25";
//            code = "C:\\Users\\tm\\AppData\\Local\\Programs\\Python\\Python39\\python D:\\test\\pathAlgorithm\\dd.py";
            String str = String.format(code);
//            str = "python --version";
            System.out.println(str);
            Process proc = Runtime.getRuntime().exec(str);//执行脚本
            proc.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream(), "GBK"));
            String line = "";
            while ((line = reader.readLine()) != null) {
                result += line + "";
            }
            reader.close();
            proc.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("返回的数据： " + result);
    }

    public static void testPython2() {
        try {
            String str = String.format("C:\\Users\\tm\\AppData\\Local\\Programs\\Python\\Python39\\python.exe D:\\test\\gpsPython\\test.py 6 4 411623 0.611255186 0.377726083 0.25");
            //System.out.println(str);
            Process proc = Runtime.getRuntime().exec("cmd");//执行脚本
            InputStream stdin = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(stdin);
            DataOutputStream os = new DataOutputStream(proc.getOutputStream());
            os.writeBytes(str + "\n");
            os.writeBytes("exit\n");
            os.flush();
            os.close();

            BufferedReader br = new BufferedReader(isr);
            char[] buffer = new char[4096];
            StringBuilder sb = new StringBuilder();

            BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            int bytesread;
            while ((bytesread = reader.read(buffer)) != -1) {
                sb.append(buffer, 0, bytesread);
            }

            System.out.println(sb.toString());
            reader.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void testPython3() {
        try {
            String str = "C:\\Users\\tm\\AppData\\Local\\Programs\\Python\\Python39\\python D:\\test\\gpsPython\\test.py 6 4 411623 0.611255186 0.377726083 0.25";
            Process proc = Runtime.getRuntime().exec(str);//执行脚本

            BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));

            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
            proc.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
    public static String imageBase64(String imgFile) {
        //待处理的本地图片
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        //返回Base64编码过的字节数组字符串
        String s = encoder.encode(data);
        return "data:image/png;base64," + encoder.encode(data);
    }
}
